package com.handong.handserialprogram.thread;

import android.os.Process;

import com.handong.handserialprogram.utils.JLog;

/**
 * Created by userKey on 2017/3/30.
 */

public abstract class BaseRunnable implements Runnable {

    protected static final String TAG = BaseRunnable.class.getSimpleName();
    protected boolean mIsWorking = true;
    private static final int SLEEP_TIME = 350;

    @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (mIsWorking) {
            try {
                work();
            } catch (RuntimeException e) {
                e.printStackTrace();
                JLog.d(TAG, e.toString());
                break;
            }
            if (!mIsWorking) {
                break;
            }
            try {
                Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
        releaseRes();
        JLog.d(TAG , Thread.currentThread().getId() + " thread has been stopped.");
    }

    public abstract void work() throws RuntimeException;

    /**
     * 释放资源。
     */
    public abstract void releaseRes();

    /**
     * 关闭线程。
     */
    public void destroy() {
        mIsWorking = false;
    }
}
